package notice.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import mq.service.impl.MqMessageCumulateServiceImpl;
import notice.config.MQDeductionConfig;
import notice.dto.DeductionNoticeDto;
import notice.dto.OrderNoticeDto;
import notice.service.impl.DeductionNoticeManagement;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @description: 消费"扣款结果通知"队列中的消息
 * @author: zk
 * @since: 2022-08-16 15:09
 */
@Slf4j
@Component
public class DeductionNoticeQueueConsumer {
    @Resource
    private MessageConverter messageConverter;
    @Resource
    private DeductionNoticeManagement deductionNoticeManagement;
    //@Resource
    //private MailServiceUtil mailServiceUtil;
    @Resource
    private MqMessageCumulateServiceImpl mqMessageCumulateServiceImpl;
    //@Value("${mail.toEmil}")
    //private String toEmil;


    @RabbitListener(queues = {MQDeductionConfig.QUEUE_DEDUCTION_NOTICE})
    public void consumeMessage(Message message, Channel channel) throws IOException {
        log.debug("扣款结果通知收到消息 message={}", message);
        try {
            DeductionNoticeDto deductionNotice = (DeductionNoticeDto) messageConverter.fromMessage(message);
            log.info("扣款结果通知处理消息 deductionNotice={}", deductionNotice);
            // 查询订单
            //OrderNoticeDto orderNoticeDto = mqMessageCumulateServiceImpl.getDeductionNotice(deductionNotice.getOrderType(), deductionNotice.getOrderNo(),deductionNotice.getCurrPayChannel());
            OrderNoticeDto orderNoticeDto = null;// 原代码为上句，让代码不报错
            Assert.notNull(orderNoticeDto,"查不到订单信息！orderNo="+deductionNotice.getOrderNo()+ ",orderType="+deductionNotice.getOrderType());

            // 业务分发处理
            deductionNoticeManagement.notifyAllObservers(orderNoticeDto);
            // 手动签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("扣款结果通知处理失败!",e);
            // 拒绝消息-会发送发死信队列中
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);

            // 立即邮件预警
            //mailServiceUtil.sendMail(toEmil, "扣款通知队列消费者处理异常 message=" + JSONObject.toJSONString(message)
            //                + " e="+e+" 请尽快核对处理",
            //        "【扣款通知队列】消费者处理异常预警");

        }
    }
}